<template>
  <div class="cont" id="map" ref="mapChart"></div>
  <div class="back-zj" v-if="isShowBackZj" @click="backZj">返回浙江省</div>
  <ul class="menu">
    <li 
      v-for="(item, index) in effectMenu" 
      :class="{active: currentIndex === index}" 
      :key="index" 
      @click="changeEffect(item.name, index)"
      >
      {{ item.name }}
    </li>
  </ul>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue'

import ZJJson from '@/assets/mapJson/zhejiang.json'
import themeMapJson from "@/assets/bdmap/custom_map_config.json";

import areaMaps, { areaPos } from '@/utils/map_utils'
import { scatter, trans, heat, seriesColor } from './config'
import * as mapVgl from 'mapvgl' 
  const BMapGL = window.BMapGL;

  const effectMenu = ref([
    { name: '基础地图' },
    { name: '热力图' },
    { name: '涟漪图' },
    { name: '多色地图' },
    { name: '运输路线' },
  ])
  const currentIndex = ref(0)
  const isShowBackZj = ref(false)
  const backZj = () => {
    initMap()
  }
  const changeEffect = (name: string, index) => {
    currentIndex.value = index
    scatterMarkers.forEach(item => item.hide())
    switch (name) {
      case '基础地图':
        initMap()
        break;
      case '涟漪图':
        initMap()
        addScatterMarker()
        break;
      case '运输路线':
        addTransMarker()
        break
      case '热力图':
        addHeatMarker()
        break
      case '多色地图':
        initMap(ZJJson, 'seriesColor')
        break
      default:
        break;
    }
  }

  let BdMap
  const initMap = (mapJson = ZJJson, type = '') => {
    BdMap = new BMapGL.Map("map");
    BdMap.centerAndZoom(
      new BMapGL.Point(...mapJson.features[0].properties.center),
      8
    );
    BdMap.enableScrollWheelZoom(true);
    BdMap.setMapStyleV2({ styleJson: themeMapJson });

    addMapOverlay(mapJson, type)
  }
  const addMapOverlay = (mapJson = ZJJson, type = '') => {
    // 绘制区边界
    mapJson.features.forEach((city) => {
      let color = '#008aff'
      if (type === 'seriesColor') {
        const target = seriesColorData.value.find(item => item.name === city.properties.name)
        if (target) {
          if(target.value > 0.5) {
            color = '#258AA0'
          }
          else if(target.value > 0.3) {
            color = '#313CCC'
          } else if(target.value > 0.2) {
            color = '#AE9325'
          } 
          else if(target.value > 0.1){
            color = '#AE6425'
          } else {
            color = '#AD1D1C'
          }
        }
      }
      const coordinateString = city.geometry.coordinates[0][0].join(";");
      const cityLine = _makePolylineData(coordinateString);
      const name = city.properties.name;
      for (let i = 0; i < cityLine.length; i++) {
        const ply = new BMapGL.Polyline(cityLine[i], {
          strokeColor: color,
          strokeWeight: 1,
        });
        BdMap.addOverlay(ply);

        const plg = new BMapGL.Polygon(cityLine[i], {
          fillColor: color,
          fillOpacity: 0.2,
        });
        plg.customData = { name };
        BdMap.addOverlay(plg);
      }
      const point = new BMapGL.Point(...city.properties.center);
      const label = new BMapGL.Label(name, {
        position: point,
      });
      label.setStyle({
        color: "#fff",
        fontSize: "14px",
        border: "1px solid #C5D4E8 ",
        borderRadius: "4px",
        backgroundColor: "#0A1937",
        padding: "2px 6px",
      });
      label.on('click', (params) => {
        isShowBackZj.value = true

        const cityName = params.currentTarget.content
        const currentItem = areaMaps.find(item => item.label === cityName)
        if (currentItem) {
          initMap(currentItem.mapJson as any)
        }
      })
      BdMap.addOverlay(label);
    })
  }

  // 构建边界数组
  const _makePolylineData = (data) => {
    const arr: any[] = [];
    data.split("|").forEach((item, i) => {
      if (!arr[i]) arr[i] = [];
      item.split(";").forEach((sItem) => {
        const lnglat = sItem.split(",");
        arr[i].push(new BMapGL.Point(Number(lnglat[0]), Number(lnglat[1])));
      });
    });
    return arr;
  }

  const scatterData = ref(scatter)
  const scatterMarkers: any[] = []
  const addScatterMarker = () => {
    scatterData.value.forEach(item => {
      const area = areaPos.find( (a) => a.name === item.name );
      if (area) {
        const pos = area.lnglat.split(",");
        let point = new BMapGL.Point(pos[0], pos[1]);
        const myIcon = new BMapGL.Label("", {
          position: point,
          offset: new BMapGL.Size(-25, -10),
        });
        myIcon.setStyle({
          width: "120px",
          height: `120px`,
          border: "none",
          backgroundColor: "transparent",
        });
        addScatterClass(item.count, myIcon);
        scatterMarkers.push(myIcon)
        BdMap.addOverlay(myIcon);
      }
    });
  }
  const addScatterClass = (count, marker) => {
    const ele = marker.domElement;
    if (!ele) {
      return setTimeout(() => {
        addScatterClass(count, marker);
      }, 200);
    }
    let clzName = count > 6 ? 'red-warn' : 'eye-icon';
    ele.setAttribute("class", clzName);
  }

  const transData = ref(trans)
  const addTransMarker = () => {
    console.log(transData)
  }

  const heatData = ref(heat)
  const addHeatMarker = () => {
    const view = new mapVgl.View({
      map: BdMap
    });

    const layer = new mapVgl.HeatmapLayer ({
      color: 'rgba(50, 50, 200, 1)',
      blend: 'lighter',
      size: 20
    });
    view.addLayer(layer);

    const regularData: any[] = []
    heatData.value.forEach(item => {
      regularData.push({
        geometry: {
          type: 'Point',
          coordinates: [item[0], item[1]]
        },
        properties: {
          count: item[2]
        }
      });
    });

    layer.setData(regularData);
  }

  const seriesColorData = ref(seriesColor)

  onMounted(() => {
    initMap()
  })
</script>

<style scoped lang="less">
.cont {
  height: 90%;
}
.menu {
  display: flex;
  justify-content: space-around;
li {
  width: 120px;
  height: 30px;
  line-height: 30px;
  border-radius: 30px;
  border: 1px solid pink;
  cursor: pointer;
}
}
.back-zj {
  cursor: pointer;
  color: rgb(86, 237, 237);
}
.active {
  background-color: pink;
}

:deep(.eye-icon) {
  background: url("../../../assets/images/chengWarning.png") no-repeat center center;
  background-size: 100% 100%;
}
:deep(.red-warn) {
  background: url("../../../assets/images/red_warning.png") no-repeat center center;
  background-size: 100% 100%;
}
</style>